package newkfp;

import Beans.AddedItem;
import com.sun.jersey.api.client.filter.Filterable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import newkfp.util.JsfUtil;
import newkfp.util.PaginationHelper;

@ManagedBean(name = "customerController")
@SessionScoped
public class CustomerController implements Serializable {
private List<Customer> listItems;
    private String customerName = "";
    private Date fromDate;
    private Date toDate;
    private Customer selectedCustomer;
    private Customer current;
    private DataModel items = null;
    private DataModel bill_items = null;
    @EJB
    private newkfp.LogFacade logFacade;
    @EJB
    private newkfp.CustomerFacade ejbFacade;
    @EJB
    private newkfp.TreausryFacade treausryFacade;
    @EJB
    private BillItemFacade billItemFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private PaginationHelper paginationBills;
    private DataModel itemsBills = null;
    public static Loger loger;
    private Boolean boolean1 = false;
    @ManagedProperty(value = "#{customerBillItemsController}")
    CustomerBillItems customerBillItems;

    public CustomerController() {
        loger = new Loger(getLogFacade());
    }

    public Customer getSelected() {
        if (current == null) {
            current = new Customer();
            selectedItemIndex = -1;
        }
        return current;
    }

    private CustomerFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(getFacade().count()) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public PaginationHelper getBillItemPagination() {
        if (paginationBills == null) {
            paginationBills = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    Calendar calendar = Calendar.getInstance();
                    if (toDate != null) {
                        calendar.setTime(toDate);
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    return new ListDataModel(getFacade().getCustomerBillAtPeriod(getSelectedCustomer().getIdCustomer(), fromDate, calendar.getTime()));
                }
            };
        }
        return paginationBills;
    }

    public String prepareList() {
        current = null;
        recreateModel();
        return "customer";
    }

    public String prepareBillItemList() {
        recreateModel();
        return "gard_3omala";
    }

    public String prepareView(Customer c) {
        current = c;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        if (current.getBalance() < 0) {
            boolean1 = true;
        } else {
            boolean1 = false;
        }
        return "View";
    }

    public String prepareCreate() {
        current = new Customer();
        selectedItemIndex = -1;
        recreateModel();
        return "customer";
    }

    public String create() {

        try {
            loger = new Loger(getLogFacade());
            System.out.println("-----customer Name: " + current.getCustomerName());
            String customerName = new String(current.getCustomerName().getBytes("UTF-8"), "UTF-8");
            System.out.println("------Name: " + customerName);
            current.setCustomerName(customerName);
            System.out.println("------customer Address: " + current.getAddress());
            String customerAddress = new String(current.getAddress().getBytes("UTF-8"), "UTF-8");
            System.out.println("------Address: " + customerAddress);
            current.setAddress(customerAddress);
            System.out.println("-------customer Others: " + current.getOther());
            String others = new String(current.getOther().getBytes("UTF-8"), "UTF-8");
            System.out.println("------others: " + others);
            current.setOther(others);
            current.setTempFlag(0);
            if (getBoolean1()) {
                current.setBalance(current.getBalance() * -1);
            }
            getFacade().create(current);
            recreateModel();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerCreated"));
            loger.LogerString("اضافة عميل جديد", 0);
//            Treausry treausry = new Treausry();
//            treausry.setActionDate(new Date());
//            treausry.setCustomerId(current);
//            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
//            treausry.setEmployeeId(new Employee(Integer.parseInt( session.getValue("empid").toString())));
//            treausry.setExporterId(null);
//            treausry.setGeneralDescription("");
//            treausry.setMoneyAmount(current.getBalance());
//            treausryFacade.create(treausry);

            return prepareCreate();
        } catch (Exception e) {
            loger.LogerString("خطاء في اضافة عميل جديد", 1);
            loger.LogerString("CustomerController : Create : " + e.getMessage(), -1);

            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit(Customer c) {
        current = c;
        
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        if (current.getBalance() < 0) {
            boolean1 = true;
            current.setBalance(current.getBalance() * -1);

        } else {
            boolean1 = false;
        }
        return "Edit";
    }

    public String update() {
        loger = new Loger(getLogFacade());

        try {
            getFacade().edit(current);
            if (getBoolean1()) {
                current.setBalance(current.getBalance() * -1);
            }
            System.out.println("cccccccccccccccc" + current.getCustomerName());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerUpdated"));
            loger.LogerString(" تم تعديل عميل بنجاح", 0);
            return "customer";
        } catch (Exception e) {
            loger.LogerString("خطاء في تعديل عميل", 1);
            loger.LogerString("CustomerController : update : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy(Customer c) {
        current = c;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        current = null;
        return "customer";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "customer";
        }
    }

    private void performDestroy() {
        loger = new Loger(getLogFacade());

        try {

            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CustomerDeleted"));
            loger.LogerString("تم حذف العميل بنجاح", 0);
        } catch (Exception e) {
            loger.LogerString("خطاء في حذف العميل", 1);
            loger.LogerString("CustomerController : Destroy : " + e.getMessage(), -1);
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        clearSession();
        System.out.println("items here");
        if (items == null) {
            items = getPagination().createPageDataModel();
           
        }
        System.out.println("items iiiii");
        return items;
    }
public List<Customer> getListItems(){
    List<Customer> customers=(List<Customer>)((javax.faces.model.DataModel)getItems()).getWrappedData();
    System.out.println(   customers.contains(new Customer(-1)));
    customers.remove(new Customer(-1));
   return customers;
}

    private void recreateModel() {
        items = null;
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "customer";
    }

    public String nextBillItem() {
        getPaginationBills().nextPage();
        recreateModel();
        return "gard_3omala";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "customer";
    }

    public String previousBillItem() {
        getPaginationBills().previousPage();
        recreateModel();
        return "gard_3omala";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     * @return the customerName
     */
    public String getCustomerName() {
        return customerName;
    }

    /**
     * @param customerName the customerName to set
     */
    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    /**
     * @return the fromDate
     */
    public Date getFromDate() {
        return fromDate;
    }

    /**
     * @param fromDate the fromDate to set
     */
    public void setFromDate(Date fromDate) {
        this.fromDate = fromDate;
    }

    /**
     * @return the toDate
     */
    public Date getToDate() {
        return toDate;
    }

    /**
     * @param toDate the toDate to set
     */
    public void setToDate(Date toDate) {
        this.toDate = toDate;
    }

    /**
     * @return the bill_items
     */
    public DataModel getBill_items() {
        paginationBills = null;
        bill_items = null;
        if (getSelectedCustomer() != null) {
            bill_items = getBillItemPagination().createPageDataModel();
            System.out.println("Bill Items: " + bill_items.getRowCount());
        }
        return bill_items;
    }

    /**
     * @param bill_items the bill_items to set
     */
    public void setBill_items(DataModel bill_items) {
        this.bill_items = bill_items;
    }

    /**
     * @return the selectedCustomer
     */
    public Customer getSelectedCustomer() {
        selectedCustomer = getFacade().getCustomerByName(getCustomerName());
        return selectedCustomer;
    }

    /**
     * @param selectedCustomer the selectedCustomer to set
     */
    public void setSelectedCustomer(Customer selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    @FacesConverter(forClass = Customer.class)
    public static class CustomerControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CustomerController controller = (CustomerController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "customerController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Customer) {
                Customer o = (Customer) object;
                return getStringKey(o.getIdCustomer());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CustomerController.class.getName());
            }
        }
    }

    public DataModel getItemsBills() {
        itemsBills = getPaginationBills().createPageDataModel();
        return itemsBills;
    }

    public PaginationHelper getPaginationBills() {


        if (paginationBills == null) {
            paginationBills = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().getBillsCustomer(current.getIdCustomer()));
                }
            };
        }
        return paginationBills;
    }

    public String bills(Customer c) {
        current = c;
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "CustomerBills";
    }

    public List<String> autocomplete(String inputValue) {
        System.out.println(" input value         --------------------------------------------------" + inputValue);
        List<Customer> objList = getFacade().getCustomerByNameOrID(inputValue);
        System.out.println(" size is " + objList.size());
        List<String> df = new ArrayList<String>();
        for (Iterator<Customer> it = objList.iterator(); it.hasNext();) {
            Customer emp = it.next();
            df.add(emp.getCustomerName());
        }
        return df;
    }

    public Double getBillTotal() {
        return getFacade().getBillTotal();
    }

    public Double getBillCach() {
        return getFacade().getBillCach();
    }

    public Double getBillRemainder() {
        return getFacade().getBillRemain();
    }

    public Double getDiscount() {
        return getFacade().getBillDisCount();
    }

    public LogFacade getLogFacade() {
        return logFacade;
    }

    public void setLogFacade(LogFacade logFacade) {
        this.logFacade = logFacade;
    }

    public TreausryFacade getTreausryFacade() {
        return treausryFacade;
    }

    public void setTreausryFacade(TreausryFacade treausryFacade) {
        this.treausryFacade = treausryFacade;
    }

    public Boolean getBoolean1() {
        return boolean1;
    }

    public void setBoolean1(Boolean boolean1) {
        this.boolean1 = boolean1;
    }

    public void clearSession() {
        Map m = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        m.remove("exporterController");

        m.remove("employeeController");
//m.remove("customerController"); 
        m.remove("countryController");
        m.remove("billInformationController");
        m.remove("inventoryStoreController");
        m.remove("moneyController");
        m.remove("billConfirmController");
        m.remove("billExporterInformationController");
        m.remove("logController");
        m.remove("itemController");

    }

    public CustomerBillItems getCustomerBillItems() {
        return customerBillItems;
    }

    public void setCustomerBillItems(CustomerBillItems customerBillItems) {
        this.customerBillItems = customerBillItems;
    }
    /*
     * View Customer Bill Details
     */
    public String viewCustomerBill(Bill bill) {
        customerBillItems.setBillNumber(bill.getBillNumber());
        customerBillItems.setDocNumber(bill.getDocNum());
        customerBillItems.setCustomerName(bill.getCustomerID().getCustomerName());
        customerBillItems.setSelectedCustomer(bill.getCustomerID());
        customerBillItems.setBillTotal(bill.getBillTotal());
        customerBillItems.setPaied(bill.getBillCach());
        customerBillItems.setBill_reminder(bill.getBillReminder());
        customerBillItems.setAdd_Item(createAddedItemList(getBillItemFacade().getItemsByBillId(bill.getIdBill())));
        customerBillItems.setBill(bill);
        customerBillItems.setBillDate(bill.getCreateDate());
        return "viewCustomerBill";
    }

    private ArrayList<AddedItem> createAddedItemList(Collection<BillItem> billItems) {
        ArrayList<AddedItem> addedItems = new ArrayList<AddedItem>();
        for (BillItem billItem : billItems) {
            if (billItem.getExportBill() == 0) {
                addedItems.add(new AddedItem(billItem.getFactoryID().getIdcountry().getCountryName(), billItem.getFactoryID().getFactoryName(), billItem.getItemID().getItemName(), billItem.getItemPrice(), billItem.getTotalPrice(), billItem.getPackageCount(), billItem.getItemAmount(), null, false,billItem.getBillItemStatus()));
            } else {
                addedItems.add(new AddedItem(billItem.getFactoryID().getIdcountry().getCountryName(), billItem.getFactoryID().getFactoryName(), billItem.getItemID().getItemName(), billItem.getItemPrice(), billItem.getTotalPrice(), billItem.getPackageCount(), billItem.getItemAmount(), null, true,billItem.getBillItemStatus()));
            }
        }
        return addedItems;
    }

    public BillItemFacade getBillItemFacade() {
        return billItemFacade;
    }

    public void setBillItemFacade(BillItemFacade billItemFacade) {
        this.billItemFacade = billItemFacade;
    }
     public void setListItems(List<Customer> listItems) {
        this.listItems = listItems;
    }
    public String destroyCustomerBill() {
        current = (Customer) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        current = null;
        return "customer";
    }
}
